import '../../public.dart';

class SellGiftCardPage extends StatefulWidget {
  const SellGiftCardPage({super.key});

  @override
  State<SellGiftCardPage> createState() => _SellGiftCardPageState();
}

class _SellGiftCardPageState extends State<SellGiftCardPage> {
  List<SysGiftCardTypeEntity> giftCardTypes = [];
  List<SysGiftCardTypeEntity> filteredGiftCardTypes = [];
  String searchQuery = '';
  bool isLoading = false;

  @override
  void initState() {
    super.initState();
    _loadGiftCardTypes();
  }

  Future<void> _loadGiftCardTypes() async {
    setState(() {
      isLoading = true;
    });
    try {
      final response = await GiftcardApi.typetList_1();
      setState(() {
        // 过滤掉 status 为 0 的礼品卡类型
        giftCardTypes =
            response.content?.where((type) => type.status == 1).toList() ?? [];
        filteredGiftCardTypes = giftCardTypes;
      });
    } catch (e) {
      debugPrint('Failed to load gift card types: $e');
      setState(() {
        giftCardTypes = [];
        filteredGiftCardTypes = [];
      });
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  void _filterGiftCardTypes(String query) {
    setState(() {
      searchQuery = query;
      if (query.isEmpty) {
        filteredGiftCardTypes = giftCardTypes;
      } else {
        final lowerCaseQuery = query.toLowerCase();
        filteredGiftCardTypes = giftCardTypes.where((card) {
          return card.typeName?.toLowerCase().contains(lowerCaseQuery) ?? false;
        }).toList();
      }
    });
  }

  void _selectGiftCardType(SysGiftCardTypeEntity cardType) {
    // 跳转到礼品卡详情页面
    debugPrint(
      'Selected gift card type: ${cardType.typeName}, ID: ${cardType.id}',
    );
    RouterHelper.navigator.pushNamed(
      Routers.sellGiftCardDetail,
      arguments: {
        'cardTypeId': cardType.id,
        'cardTypeName': cardType.typeName ?? '',
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        title: const Text('Sell Gift Cards'),
        elevation: 0,
      ),
      body: SafeArea(
        child: isLoading
            ? const Center(child: CircularProgressIndicator())
            : Column(
                children: [
                  // 搜索框
                  Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(8.0),
                        border: Border.all(
                          color: Colors.grey.shade300,
                          width: 1.0,
                        ),
                      ),
                      child: Row(
                        children: [
                          const Padding(
                            padding: EdgeInsets.only(left: 12),
                            child: Icon(Icons.search, color: Colors.grey),
                          ),
                          Expanded(
                            child: TextField(
                              onChanged: _filterGiftCardTypes,
                              decoration: const InputDecoration(
                                hintText: 'Search for card',
                                border: InputBorder.none,
                                contentPadding: EdgeInsets.symmetric(
                                  vertical: 12,
                                  horizontal: 12,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  // 礼品卡类型网格
                  Expanded(
                    child: GridView.builder(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 16.0,
                        vertical: 8.0,
                      ),
                      gridDelegate:
                          const SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 2,
                            crossAxisSpacing: 16.0,
                            mainAxisSpacing: 16.0,
                            childAspectRatio: 1.5,
                          ),
                      itemCount: filteredGiftCardTypes.length,
                      itemBuilder: (context, index) {
                        final cardType = filteredGiftCardTypes[index];
                        return CardTypeButton(
                          title: cardType.typeName ?? '',
                          imageUrl: cardType.iconUrl ?? '',
                          onTap: () => _selectGiftCardType(cardType),
                        );
                      },
                    ),
                  ),
                ],
              ),
      ),
    );
  }
}

class CardTypeButton extends StatelessWidget {
  final String title;
  final VoidCallback onTap;
  final String? imageUrl;

  const CardTypeButton({
    super.key,
    required this.title,
    required this.onTap,
    required this.imageUrl,
  });

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(8.0),
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8.0),
          border: Border.all(color: Colors.grey.shade300, width: 1.0),
          image: imageUrl != null
              ? DecorationImage(
                  image: NetworkImage(CryptoUtil.decryptData(imageUrl) ?? ''),
                  fit: BoxFit.cover,
                )
              : null,
        ),
        alignment: Alignment.center,
        child: imageUrl != null
            ? null
            : Text(
                title,
                style: const TextStyle(fontSize: 16, color: Colors.black),
                textAlign: TextAlign.center,
              ),
      ),
    );
  }
}
